﻿ #region Disclaimer/Info
 
 /////////////////////////////////////////////////////////////////////////////////////////////////
 //
 //   File:		CommentRepository.cs
 //   Website:		http://dexterblogengine.com/
 //   Authors:		http://dexterblogengine.com/About.ashx
 //   Rev:		1
 //   Created:		19/01/2011
 //   Last edit:		19/01/2011
 //   License:		GNU Library General Public License (LGPL)
 //   File:            CommentRepository.cs
 //   For updated news and information please visit http://dexterblogengine.com/
 //   Dexter is hosted to Codeplex at http://dexterblogengine.codeplex.com
 //   For any question contact info@dexterblogengine.com
 //
 ///////////////////////////////////////////////////////////////////////////////////////////////////
 
 #endregion

using System;
using System.Collections.Generic;
using System.Linq;
using Dexter.Core.Data.Repository;
using Dexter.Domain.Model;
using Dexter.Domain.Results;
using Dexter.Logger.Contracts;
using Dexter.Repository.NHibernate.Queries;
using NHibernate;
using Topics.Radical.Validation;
using ISessionFactory = Dexter.Repository.NHibernate.SessionFactory.ISessionFactory;

namespace Dexter.Repository.NHibernate.Repositories {

	/// <summary>
	/// The implementation of <see cref="ICommentRepository"/>
	/// </summary>
	/// <example>The following is an example of initializing 
	///          an <c>CommentRepository</c> type:
	///   <code>
	///       // Create the type.
	///       CommentRepository ds = new CommentRepository;
	/// 
	///       if ( null == ds )
	///           return;
	/// 
	///       return ds.DoSomething( 5 );
	///   </code>
	/// </example>
	public class CommentRepository : RepositoryBase <Comment> , ICommentRepository {
		
		/// <summary>
		/// Initializes a new instance of the <see cref="CommentRepository"/> class.
		/// </summary>
		/// <param name="sessionFactory">The session factory.</param>
		/// <param name="logger">The logger.</param>
		public CommentRepository ( ISessionFactory sessionFactory , ILogger logger )
			: base ( sessionFactory , logger ) {}

		#region Implementation of ICommentRepository

		/// <summary>
		/// Adds the specified item.
		/// </summary>
		/// <param name="item">The item.</param>
		public override void Add ( Comment item ) {
			this.Save ( item );
		}

		/// <summary>
		/// Retrieve a set of approved comments with the basic properties of Item loaded.
		/// </summary>
		/// <param name="pageIndex">Index of the page (0 based).</param>
		/// <param name="pageSize">The number of items to retrieve.</param>
		/// <returns>
		/// An concrete implementation of <see cref="IPagedResult"/>. The result will never be null.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		public virtual IPagedResult<Comment> GetApprovedWithBasicItemProperties ( int pageIndex, int pageSize ) {
			return GetApprovedWithBasicItemProperties ( pageIndex , pageSize , true );
		}

		/// <summary>
		/// Retrieve a set of approved comments with the basic properties of Item loaded.
		/// </summary>
		/// <param name="pageIndex">Index of the page (0 based).</param>
		/// <param name="pageSize">The number of items to retrieve.</param>
		/// <param name="enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		/// <returns>
		/// An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		public virtual IPagedResult<Comment> GetApprovedWithBasicItemProperties ( int pageIndex, int pageSize, bool enableTracking ) {
			Ensure.That ( pageIndex )
				.Named ( "pageIndex" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsGreaterThen ( 0 , Or.Equal )
				.WithMessage ( "Invalid page index." );

			Ensure.That ( pageSize )
				.Named ( "pageSize" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsGreaterThen ( 0 )
				.WithMessage ( "Invalid page size." );


			IFutureValue <long> total = Session.GetNamedQuery ( KnownQueries.CommentRepository.GetApprovedWithBasicItemPropertiesCount )
				.SetReadOnly ( true )
				.FutureValue <long> ( );

			IEnumerable <Comment> result = Session.GetNamedQuery ( KnownQueries.CommentRepository.GetApprovedWithBasicItemProperties )
				.SetFirstResult ( pageIndex * pageSize )
				.SetMaxResults ( pageSize )
				.SetReadOnly ( !enableTracking )
				.Future <Comment> ( );

			return new PagedResult<Comment>(pageIndex, pageSize, result.ToList(), total.Value);
		}

		/// <summary>
		/// Retrieve a set of unapproved comments with the basic properties of Item loaded.
		/// </summary>
		/// <param name="pageIndex">Index of the page (0 based).</param>
		/// <param name="pageSize">The number of items to retrieve.</param>
		/// <returns>
		/// An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		public virtual IPagedResult<Comment> GetUnapprovedWithBasicItemProperties ( int pageIndex, int pageSize ) {
			return GetUnapprovedWithBasicItemProperties ( pageIndex , pageSize , true );
		}

		/// <summary>
		/// Retrieve a set of unapproved comments with the basic properties of Item loaded.
		/// </summary>
		/// <param name="pageIndex">Index of the page (0 based).</param>
		/// <param name="pageSize">The number of items to retrieve.</param>
		/// <param name="enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		/// <returns>
		/// An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		public virtual IPagedResult<Comment> GetUnapprovedWithBasicItemProperties ( int pageIndex, int pageSize, bool enableTracking ) {
			Ensure.That ( pageIndex )
				.Named ( "pageIndex" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsGreaterThen ( 0 , Or.Equal )
				.WithMessage ( "Invalid page index." );

			Ensure.That ( pageSize )
				.Named ( "pageSize" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsGreaterThen ( 0 )
				.WithMessage ( "Invalid page size." );

			IFutureValue <long> total = Session.GetNamedQuery ( KnownQueries.CommentRepository.GetUnapprovedWithBasicItemPropertiesCount )
				.SetReadOnly ( true )
				.FutureValue <long> ( );

			IEnumerable <Comment> result = Session.GetNamedQuery ( KnownQueries.CommentRepository.GetUnapprovedWithBasicItemProperties )
				.SetFirstResult ( pageIndex * pageSize )
				.SetMaxResults ( pageSize )
				.SetReadOnly ( !enableTracking )
				.Future <Comment> ( );

			return new PagedResult<Comment>(pageIndex, pageSize, result.ToList(), total.Value);
		}

		/// <summary>
		/// Retrieve the latest approved comments with the basic properties of Item loaded.
		/// </summary>
		/// <param name="number">The number of items to retrieve.</param>
		/// <returns>
		/// An instance of comment.
		/// The return object could be null if there arent items unapproved into the repository.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="number"/> is lesser than 0.</exception>
		public virtual IEnumerable<Comment> GetRecentCommentWithBasicItemProperties ( int number ) {
			return GetRecentCommentWithBasicItemProperties ( number , true );
		}

		/// <summary>
		/// Retrieve the latest approved comments with the basic properties of Item loaded.
		/// </summary>
		/// <param name="number">The number of items to retrieve.</param>
		/// <param name="enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		/// <returns>
		/// An instance of comment.
		/// The return object could be null if there arent items unapproved into the repository.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="number"/> is lesser than 0.</exception>
		public virtual IEnumerable<Comment> GetRecentCommentWithBasicItemProperties ( int number, bool enableTracking ) {
			Ensure.That ( number )
				.Named ( "number" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsGreaterThen ( 1 , Or.Equal )
				.WithMessage ( "The paramenter number should be greater then 0." );

			IEnumerable <Comment> result = Session.GetNamedQuery ( KnownQueries.CommentRepository.GetRecentCommentWithBasicItemProperties )
				.SetMaxResults ( number )
				.SetReadOnly ( !enableTracking )
				.List <Comment> ( );

			return result;
		}

		/// <summary>
		/// Retrieve the latest approved comments with the basic properties of Item loaded.
		/// </summary>
		/// <param name="key">The key of the comment.</param>
		/// <returns>
		/// An instance of comment.
		/// The return object could be null if there isn't a comment with the specified key into the repository.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="key"/> is lesser than 0.</exception>
		public virtual Comment GetByKeyWithBasicItemProperties ( int key ) {
			return GetByKeyWithBasicItemProperties ( key , true );
		}

		/// <summary>
		/// Retrieve the latest approved comments with the basic properties of Item loaded.
		/// </summary>
		/// <param name="key">The key of the comment.</param>
		/// <param name="enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		/// <returns>
		/// An instance of comment.
		/// The return object could be null if there isn't a comment with the specified key into the repository.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="key"/> is lesser than 0.</exception>
		public virtual Comment GetByKeyWithBasicItemProperties ( int key, bool enableTracking ) {
			Ensure.That ( key )
				.Named ( "key" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsGreaterThen ( 0 )
				.WithMessage ( "Invalid comment Key." );

			var result = Session.GetNamedQuery ( KnownQueries.CommentRepository.GetByKeyWithBasicItemProperties )
				.SetParameter ( "key" , key )
				.SetReadOnly ( !enableTracking )
				.UniqueResult <Comment> ( );

			return result;
		}

		/// <summary>
		/// Deletes all unapproved comment from the repository.
		/// </summary>
		/// <returns>The number of comments deleted.</returns>
		public virtual int DeleteAllUnapprovedComment ( ) {
			int rowsDeleted = 0;
			IEnumerable <Comment> result = Session.GetNamedQuery ( KnownQueries.CommentRepository.GetUnapprovedWithBasicItemProperties )
				.List <Comment> ( );

			foreach ( Comment comment in result ) {
				comment.ValidateForDelete ( );
				Session.Delete ( comment );
				rowsDeleted++;
			}

			return rowsDeleted;
		}

		/// <summary>
		/// Saves the specified item into the repository.
		/// </summary>
		/// <param name="item">The item to save.</param>
		/// <exception cref="ArgumentNullException"> If <paramref name="item"/> is <c>null</c>.</exception>
		public virtual void Save ( Comment item ) {
			Ensure.That ( item )
				.Named ( "item" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsNotNull ( )
				.WithMessage ( "Invalid comment." );

			item.ValidateForSave ( );

			Session.SaveOrUpdate ( item );
		}

		/// <summary>
		/// Updates the specified item into the repository.
		/// </summary>
		/// <param name="item">The item to update.</param>
		/// <exception cref="ArgumentNullException"> If <paramref name="item"/> is <c>null</c>.</exception>
		public virtual void Update ( Comment item ) {
			Ensure.That ( item )
				.Named ( "item" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsNotNull ( )
				.WithMessage ( "Invalid comment." );

			item.ValidateForUpdate ( );

			Session.SaveOrUpdate ( item );
		}

		#endregion
	}
}
